package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.StageLogHelp;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.service.CustomerRuleService;
import com.xbongbong.paas.service.TransferBackRuleScriptService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FocusDTO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.message.constant.OpportunityPushConstant;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.help.PushHelper;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.service.MessageService;
import com.xbongbong.pro.opportunity.pojo.JudgeStageChangedPojo;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.OpportunityProductEntity;
import com.xbongbong.saas.domain.entity.OpportunityStageLogEntity;
import com.xbongbong.saas.domain.entity.OpportunityUserEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.RuleSettingEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.help.workflow.MarketActivityForStaticHelp;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OpportunityProductModel;
import com.xbongbong.saas.model.OpportunityStageLogModel;
import com.xbongbong.saas.model.OpportunityUserModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.service.ConsistencySyncService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.OpportunityService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.help.saas.WorkFlowSaasStageHelp;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getStringOrDefaultFromFormData;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowOpportunityStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private UserModel userModel;
    @Resource
    private PushHelper pushHelper;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private CustomerRuleService customerRuleService;
    @Resource
    private OpportunityService opportunityService;
    @Resource
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private StageLogHelp stageLogHelp;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private MarketActivityForStaticHelp marketActivityForStaticHelp;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private OpportunityUserModel opportunityUserModel;
    @Resource
    private OpportunityProductModel opportunityProductModel;
    @Resource
    private MessageService messageService;
    @Resource
    private ConsistencySyncService consistencySyncService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private WorkFlowSaasStageHelp workFlowSaasStageHelp;
    @Resource
    private OpportunityStageLogModel opportunityStageLogModel;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private TransferBackRuleScriptService transferBackRuleScriptService;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        Long formId = pojoData.getFormId();
        User user = workflowTransferPOJO.getUser();

        Integer subBusiniessType = pojoData.getSubBusinessType();

        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), 0L);
        List<Long> contactIds = FastJsonHelper.getTransferTypesFromData(data, SalesOpportunityEnum.CONTACT_NAME.getAttr(), Long.class);
        String salesStageCode = getStringOrDefaultFromFormData(data, SalesOpportunityEnum.SALE_STAGE.getAttr(), "");
        Integer reasonId = getIntegerOrDefaultFromFormData(data, SalesOpportunityEnum.WASTAGE.getAttr(), BasicConstant.ZERO);
        String wastageMemo = FastJsonHelper.getStringOrDefaultFromFormData(data, SalesOpportunityEnum.WASTAGE_MEMO.getAttr(), "");
        String opportunityName = FastJsonHelper.getStringOrDefaultFromFormData(data, SalesOpportunityEnum.NAME.getAttr(), "");

        String creatorId = user.getUserId();
        UserEntity creatorUser = userModel.getByKeyIngoreDel(creatorId, corpid);
        JudgeStageChangedPojo judgeStageChangedPojo = null;
        try {
            // 新建更新客户最后联系时间
            long lastConnectTime = DateUtil.getInt();
            CustomerEntityExt customerEntityExt = customerModel.getByKey(customerId, corpid);
            //新建销售机会，取其创建时间更新影响客户最后跟进时间
            Boolean flag = proFormHelp.getSingleRuleList(corpid, RuleSettingEnum.NEW_OPPORTUNITIES_CREATE_TIME.getConfig(), customerEntityExt.getFormId());
            if (flag) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), lastConnectTime);
                UpdateDataEntity updateData = ExplainUtil.getUpdateData(customerId, jsonObject, corpid);
                customerModel.updateBatch(Collections.singletonList(updateData), corpid);
            }

            //更新最近机会创建时间
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(CustomerManagementEnum.OPPORTUNITY_ADD_DATE.getAttr(),lastConnectTime);
            customerModel.specialUpdate4SysDate(customerId, jsonObject, corpid);

        } catch (Exception e) {
            log.error("新建机会更新客户最后联系时间", e);
        }

        try {
            CustomerEntityExt customerEntity = customerModel.getByKey(dataId, corpid);
            Long customerFormId  = customerEntity != null ? customerEntity.getFormId() : 0L;

            if (commonHelp.isCustomerPublicPoolSeniorModel(corpid)){
                transferBackRuleScriptService.deletePublicSeniorTag(corpid, Collections.singletonList(dataId), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), customerFormId);
            }else {
                customerRuleService.deletePublicTag(corpid, Collections.singletonList(dataId));
            }
        } catch (Exception e) {
            log.error("新建机会动态去除客户标签", e);
        }

        try {
            if (Objects.equals(subBusiniessType, XbbRefTypeEnum.KEY_OPPORTUNITY.getCode())) {
                // 重点机会关注
                if (Objects.equals(pojoData.getSubBusinessType(), XbbRefTypeEnum.KEY_OPPORTUNITY.getCode())) {
                    FocusDTO focusDTO = new FocusDTO();
                    focusDTO.setBusinessType(pojoData.getBusinessType());
                    focusDTO.setCorpid(corpid);
                    focusDTO.setUserId(creatorId);
                    focusDTO.setDataIdList(Collections.singletonList(dataId));
                    focusDTO.setFocus(1);
                    focusDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                    opportunityService.focus(focusDTO);
                }
            }
        } catch (Exception e) {
            log.error("新建机会重点机会关注", e);
        }

        // 机会创建项目日志
        try {
            if(isNotDistributeBusinessType(workflowTransferPOJO)) {
                judgeStageChangedPojo = stageLogHelp.judgeStageChanged(corpid, formId, dataId, salesStageCode, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                String customerName = data.getString(SalesOpportunityEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
                PaasFormEntity paasForm = proFormHelp.getPaasForm(pojoData.getFormId(), pojoData.getBusinessType(), corpid);
                String paasFormName = I18nMessageUtil.getMessage(I18nStringConstant.A_SALES_OPPORTUNITY);
                if (Objects.nonNull(paasForm)) {
                    paasFormName = paasForm.getName();
                }

                String memo;
                String communicateMemo;
                if (Objects.equals(workflowTransferPOJO.getIsImport(), BasicConstant.ONE)) {
                    if (StringUtil.isNotEmpty(salesStageCode) && Objects.nonNull(judgeStageChangedPojo)) {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT_STAGE;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUser.getName(), paasFormName, judgeStageChangedPojo.getTargetStageName());
                    } else {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUser.getName(), paasFormName, data.getString(BasicConstant.SERIAL_NO));
                    }
                } else {
                    if (StringUtil.isNotEmpty(salesStageCode) && Objects.nonNull(judgeStageChangedPojo)) {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_ADD_STAGE;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUser.getName(), paasFormName, judgeStageChangedPojo.getTargetStageName());
                    } else {
                        memo = CrmLogMemoConstant.DYNAMIC_USER_ADD;
                        communicateMemo = String.format(I18nMessageUtil.getMessage(memo), creatorUser.getName(), paasFormName, data.getString(BasicConstant.SERIAL_NO));
                    }
                }
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setCustomerId(customerId);
                customerDynamicAddDTO.setContactIds(contactIds);
                customerDynamicAddDTO.setOpportunityIds(Collections.singletonList(dataId));
                customerDynamicAddDTO.setCustomerName(customerName);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCommunicateBusinessText(data.getString(BasicConstant.SERIAL_NO));
                customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                customerDynamicAddDTO.setDataId(dataId);
                customerDynamicAddDTO.setLogType(ProjectLogEnum.OPPORTUNITY_CREATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }else {
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                String customerName = data.getString(SalesOpportunityEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
                String operate = Objects.equals(workflowTransferPOJO.getIsImport(), 1) ? I18nMessageUtil.getMessage(I18nStringConstant.IMPORTED) : I18nMessageUtil.getMessage(I18nStringConstant.ADD);
                String communicateMemo = "“" + creatorUser.getName() + "”" + operate + I18nMessageUtil.getMessage(I18nStringConstant.A_SALES_OPPORTUNITY) + "“" + data.getString(BasicConstant.SERIAL_NO) + "”";
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(creatorId);
                customerDynamicAddDTO.setCustomerId(customerId);
                customerDynamicAddDTO.setCustomerName(customerName);
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setCommunicateBusinessText(data.getString(BasicConstant.SERIAL_NO));
                customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                customerDynamicAddDTO.setDataId(dataId);
                customerDynamicAddDTO.setLogType(ProjectLogEnum.OPPORTUNITY_CREATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerDynamicAddDTO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }
        } catch (Exception e) {
            log.error("机会创建项目日志", e);
        }

        try {
            if (!Objects.equals(workflowTransferPOJO.getIsImport(), 1)) {
                // 新建销售机会消息推送
                OpportunityEntityExt opportunityEntityExt = new OpportunityEntityExt();
                opportunityEntityExt.setId(dataId);
                List<String> pushUserList = pushHelper.getUserIdListByPushSetRule(corpid, PushTypeEnum.OPPORTUNITY_ADD_PUSH.getCode(), PushTypeEnum.OPPORTUNITY_ADD_PUSH.getSubCode(), creatorUser, opportunityEntityExt);
                PushRefTypePojo.Options options = new PushRefTypePojo.Options(pojoData.getAppId(), pojoData.getMenuId(), pojoData.getFormId(), dataId, Collections.singletonList(dataId), SaasMarkEnum.SAAS.getCode(), pojoData.getBusinessType(), pojoData.getSubBusinessType());
                MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, pushUserList, Collections.singletonList(dataId), 0, null, I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_ADD_TITLE), String.format(I18nMessageUtil.getMessage(OpportunityPushConstant.OPPORTUNITY_ADD_CONTENT), creatorUser.getName(), data.getString(BasicConstant.SERIAL_NO)), null, options);
                messageService.delayPushDingtalkOAMessage(messageRabbitMqDTO, PushTypeEnum.OPPORTUNITY_ADD_PUSH);
            }
        } catch (Exception e) {
            log.error("新建销售机会消息推送", e);
        }

        if(Objects.isNull(judgeStageChangedPojo)) {
            judgeStageChangedPojo = stageLogHelp.judgeStageChanged(corpid, formId, dataId, salesStageCode, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        }
        if (judgeStageChangedPojo.getIsStageChanged()) {
            try {
                workFlowSaasStageHelp.workFlowStageJump(workflowTransferPOJO, SalesOpportunityEnum.SALE_STAGE.getAttr(), null);
            } catch (Exception e) {
                log.error("销售阶段变更消息推送", e);
            }
        }

        // 添加统计数据(如果关联的客户是由线索转化而来的)
        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(dataId, corpid);
        marketActivityForStaticHelp.addMarketActivity(opportunityEntityExt, XbbRefTypeEnum.SALES_OPPORTUNITY);
        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        //log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        Long dataId = pojoData.getId();
        JSONObject data = pojoData.getData();
        Long formId = pojoData.getFormId();
        User user = workflowTransferPOJO.getUser();

        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, SalesOpportunityEnum.CUSTOMER_NAME.getAttr(), 0L);
        String salesStageCode = getStringOrDefaultFromFormData(data, SalesOpportunityEnum.SALE_STAGE.getAttr(), "");
        Integer reasonId = getIntegerOrDefaultFromFormData(data, SalesOpportunityEnum.WASTAGE.getAttr(), BasicConstant.ZERO);
        String wastageMemo = FastJsonHelper.getStringOrDefaultFromFormData(data, SalesOpportunityEnum.WASTAGE_MEMO.getAttr(), "");
        String opportunityName = FastJsonHelper.getStringOrDefaultFromFormData(data, SalesOpportunityEnum.NAME.getAttr(), "");

        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
        JSONObject oldData = workflowBackupDataEntity.getData();

        String creatorId = user.getUserId();
        UserEntity creatorUser = userModel.getByKeyIngoreDel(creatorId, corpid);

        JudgeStageChangedPojo judgeStageChangedPojo = stageLogHelp.judgeStageChanged(corpid, formId, dataId, salesStageCode, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        if (judgeStageChangedPojo.getIsStageChanged()) {
            try {
                //跳转前的阶段需要从log表中实时去查一下，工作流的流转数据已经被更新过了，不能从那里拿
                OpportunityStageLogEntity opportunityStageLogEntity = opportunityStageLogModel.getIsNowStage(corpid, formId, dataId);
                PaasStageEntity saleStageEntity = null;
                if ( !Objects.isNull(opportunityStageLogEntity)) {
                    Long stageId = opportunityStageLogEntity.getStageId();
                    saleStageEntity = saleStageModel.getByKey(stageId, corpid);
                }

                workFlowSaasStageHelp.workFlowStageJump(workflowTransferPOJO, SalesOpportunityEnum.SALE_STAGE.getAttr(), saleStageEntity);
            } catch (Exception e) {
                log.error("销售阶段变更消息推送", e);
            }
        }

        // 一致性同步
        try{
            String newContractSerialNo = data.getString(BasicConstant.SERIAL_NO);
            String oldContractSerialNo = oldData.getString(BasicConstant.SERIAL_NO);
            if (!Objects.equals(oldContractSerialNo, newContractSerialNo)) {
                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, dataId, "", newContractSerialNo);
                consistencySyncService.syncOpportunity(consistencySyncRabbitMqDTO);
            }
        }catch (Exception e){
            log.error("数据一致性同步", e);
        }


        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(dataId, corpid);
        marketActivityForStaticHelp.updateMarketActivity(opportunityEntityExt, RedundantTemplateTypeEnum.SALES_OPPORTUNITY);

        try {
            if (isNotDistributeBusinessType(workflowTransferPOJO) && Boolean.FALSE.equals(judgeStageChangedPojo.getIsStageChanged())) {
                PaasFormEntity paasForm = proFormHelp.getPaasForm(pojoData.getFormId(), pojoData.getBusinessType(), corpid);
                String paasFormName = XbbRefTypeEnum.SALES_OPPORTUNITY.getName();
                if (Objects.nonNull(paasForm)) {
                    paasFormName = paasForm.getName();
                }
                String creatorUserName = Objects.isNull(creatorUser) ? "" : creatorUser.getName();
                String communicateMemo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.DYNAMIC_USER_UPDATE_BASE_INFO), creatorUserName, paasFormName);
                CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
                customerDynamicAddDTO.setCorpid(corpid);
                customerDynamicAddDTO.setUserId(user.getUserId());
                customerDynamicAddDTO.setMemo(communicateMemo);
                customerDynamicAddDTO.setOpportunityIds(Collections.singletonList(dataId));
                customerDynamicAddDTO.setDataId(0L);
                customerDynamicAddDTO.setCommunicateBusinessType(null);
                customerDynamicAddDTO.setCommunicateBusinessText("");
                customerDynamicAddDTO.setLogType(ProjectLogEnum.OPPORTUNITY_UPDATE.getSubType());
                customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowOpportunityStrategy.update", e);
        }

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException{
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                OpportunityEntityExt opportunityEntityExt = new OpportunityEntityExt();
                opportunityEntityExt.setId(dataId);
                opportunityEntityExt.setCorpid(corpid);
                opportunityEntityExt.setData(data);
                opportunityEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                // 获取负责人
                opportunityEntityExt.setOwnerId(getOwnerId(data));
                opportunityEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));
                List<OpportunityUserEntity> contractUserList = JSON.parseArray(data.getString(StringConstant.USER_TEAM), OpportunityUserEntity.class);

                List<OpportunityProductEntity> productList = JSON.parseArray(data.getString(StringConstant.PRODUCT), OpportunityProductEntity.class);

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                data.remove(StringConstant.PRODUCT);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    opportunityEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                opportunityModel.update(opportunityEntityExt);
                // 回退被删掉的子表单
                updateBackSubForm(opportunityEntityExt, corpid, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
                saveUserTeam(contractUserList, corpid, opportunityEntityExt.getId());
                saveProduct(productList, corpid, opportunityEntityExt.getId());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowOpportunityStrategy.updateBack error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            OpportunityEntityExt opportunityEntityExt = new OpportunityEntityExt();
            opportunityEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                opportunityEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                opportunityEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            opportunityEntityExt.setCorpid(corpid);
            opportunityEntityExt.setUpdateTime(DateTimeUtil.getInt());
            opportunityModel.update(opportunityEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            // 产品
            List<OpportunityProductEntity> productList = opportunityProductModel.getProductsByOppId(dataId, corpid);
            if (CollectionsUtil.isNotEmpty(productList)) {
                List<Long> deleteList = new ArrayList<>();
                productList.forEach(item->deleteList.add(item.getId()));
                opportunityProductModel.deleteBatch(deleteList, corpid, del.getDel());
            }
            // 团队
            List<OpportunityUserEntity> contractUserList = opportunityUserModel.getOpportunityUserList(corpid, dataId, null);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                opportunityUserModel.deleteBatchUser(contractUserList, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowOpportunityStrategy.approvalFailed error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveProduct(List<OpportunityProductEntity> list, String corpid, Long dataId) throws XbbException {
        try {
            List<OpportunityProductEntity> productList = opportunityProductModel.getProductsByOppId(dataId, corpid);

            // 遍历数据库中的产品
            List<Long> deleteList = new ArrayList<>();

            // 遍历备份表中的产品
            List<Long> backupProductId = new ArrayList<>();
            list.forEach(item->backupProductId.add(item.getId()));


            // 移除掉备份表中的产品
            productList.forEach(item->{
                if (!backupProductId.contains(item.getId())) {
                    deleteList.add(item.getId());
                }
            });

            if (CollectionsUtil.isNotEmpty(deleteList)) {
                opportunityProductModel.deleteBatch(deleteList, corpid, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                opportunityProductModel.updateMulti(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowContractStrategy.saveProduct error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
    /**
     * 保存团队
     * @param list
     * @param corpid
     * @param dataId
     * @throws XbbException
     */
    private void saveUserTeam(List<OpportunityUserEntity> list, String corpid, Long dataId) throws XbbException {

        try {
            List<OpportunityUserEntity> contractUserList = opportunityUserModel.getOpportunityUserList(corpid, dataId, null);
            List<Long> idList = new ArrayList<>();
            list.forEach(item->idList.add(item.getId()));

            contractUserList.removeIf(item->idList.contains(item.getId()));

            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                opportunityUserModel.deleteBatchUser(contractUserList, corpid, DelEnum.DELETE.getDel());
            }
            if (CollectionsUtil.isNotEmpty(list)) {
                opportunityUserModel.updateBatch(list, corpid);
            }


        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowMarketActivityStrategy.saveUserTeam error ", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
